package com.jackeysun.common.view

import android.view.View
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext

/**
 *   Created by sunxunchao on 2021/12/27.
 */

fun View.visible() {
    visibility = View.VISIBLE
}

fun View.gone() {
    visibility = View.GONE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

fun View.isVisible() = visibility == View.VISIBLE

suspend fun View.h(): Int =
    withContext(Dispatchers.Main) {
        try {
            suspendCancellableCoroutine {
                post {
                    it.takeIf { isActive }?.resumeWith(Result.success(this@h.height))
                }
            }
        } catch (e: Throwable) {
            0
        }
    }

suspend fun View.w(): Int =
    withContext(Dispatchers.Main) {
        try {
            suspendCancellableCoroutine {
                post {
                    it.takeIf { isActive }?.resumeWith(Result.success(this@w.width))
                }
            }
        } catch (e: Throwable) {
            0
        }
    }


fun View.getHeight2(): Int {
    measure(0, 0)
    return this.measuredHeight
}

fun View.getWidth2(): Int {
    measure(0, 0)
    return this.measuredWidth
}
